import { request, storage } from '@doctorwork/saga';
import pick from 'lodash.pick';

export default {
    namespace: 'addressEdit',
    state: {
        siteData: {},
        district: ''
    },
    reducers: {
        saveDetail(state, { payload }) {
            return Object.assign({}, state, { ...payload });
        }
    },
    effects: {
        *saveForm({ payload }, { put }) {
            yield put.resolve(
                request.post({
                    url: payload.url,
                    data: payload.data
                })
            );
            if (payload.isOrder) {
                yield put.resolve(storage.set('userAddress', payload.data));
                yield put({
                    type: 'goodsOrder/getAddressById',
                    payload: {
                        id: payload.data.id
                    }
                });
            }

            yield put({
                type: '$router/back'
            });
        },

        *getDetail({ payload }, { put }) {
            const res = yield put.resolve(
                request.get({
                    url: '/api/user/address/query'
                })
            );

            let resData = res.map(item => {
                let address = String(
                    item.provinceName +
                        ',' +
                        item.cityName +
                        ',' +
                        item.districtName
                );
                let pickData = pick(item, [
                    'userName',
                    'mobile',
                    'isDefault',
                    'id',
                    'district',
                    'street',
                    'city',
                    'province',
                    'district'
                ]);
                pickData.address = address;
                return pickData;
            });
            if (!res.errcode) {
                let siteData = resData.filter(item => {
                    return item.id == payload.id;
                })[0];

                yield put({
                    type: 'saveDetail',
                    payload: {
                        siteData
                    }
                });
            }
        }
    }
};
